/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.peer.ui.async.gui;

import javax.swing.JOptionPane;

import org.ourgrid.peer.ui.async.client.PeerAsyncInitializer;
import org.ourgrid.peer.ui.async.util.XMPPUtils;

import br.edu.ufcg.lsd.commune.CommuneRuntimeException;

/**
 * AddUserDialog provides a simple mechanism for the user to add an User.
 */
public class AddUserDialog extends javax.swing.JDialog {
    private static final String DEFAULT_SECURE_PORT = "5223";

	private static final String DEFAULT_SERVER_PORT = "5222";

	private static final long serialVersionUID = 1L;
	
	/** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;
    
    /** Creates new form AddUserDialog */
    public AddUserDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
    public int getReturnStatus() {
        return returnStatus;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        //addUserCheckBox = new javax.swing.JCheckBox();
        userRegistrationPanel = new org.ourgrid.peer.ui.async.gui.UserRegistrationPanel();

        setTitle("Add User");
        setModal(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        okButton.setText("Add");
        okButton.setName("Add");

        cancelButton.setText("Cancel");
        
        //addUserCheckBox.setText("Add user to XMPP");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap(278, Short.MAX_VALUE)
                .add(okButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(cancelButton)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                //.add(addUserCheckBox)
                .addContainerGap(281, Short.MAX_VALUE))
            .add(userRegistrationPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
        );

        layout.linkSize(new java.awt.Component[] {cancelButton, okButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(userRegistrationPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(8, 8, 8)
                //.add(addUserCheckBox)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 8, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(cancelButton)
                    .add(okButton))
                .addContainerGap())
        );

        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });
        
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        
        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * Confirm the addition of a new User.
     * @param evt The event the represents the clicking of the ok button.
     */
    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        if (!addPeerUser()) {
        	return;
        }
    	doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed
    

    /**
     * Add a new peer user to the user File.
     * @return <code>true</code> if the peer user have been added sucesfully.
     */
	private boolean addPeerUser() {
    	
		String userName = userRegistrationPanel.getUserName();
		String userServer = userRegistrationPanel.getServer();
		String login = userName + '@' + userServer;
		String password = new String(userRegistrationPanel.getPassword());
		String retypePassword = new String(userRegistrationPanel.getRetypePassword());
		
		if (!password.equals(retypePassword)) {
        	JOptionPane.showMessageDialog(null, "Passwords do not match", 
        			"Passwords do not match", JOptionPane.ERROR_MESSAGE);
        	return false;
        }
		
		if (!addPeerUser(login, password)) {
			return false;
		}
		
		/*if (addUserCheckBox.isSelected()) {
        	addXMPPUser(userName, userServer, password); 
        }*/
		
		return true;
		
	}

	/**
	 * Add the peer user that has the login and password provided.
	 * @param login The login of the peer user that will be added.
	 * @param password The password of the peer user that will be added.
	 * @return <code>true</code> if the peer user have been added successfully.
	 */
	private boolean addPeerUser(String login, String password) {
		/*File userFile = new File(PeerConfiguration.USERS_FILENAME);
		Properties usersProperties = CommonUtils.loadProperties(userFile);
		
		usersProperties.setProperty(login + PeerConfiguration.USERS_PROPERTIES_SEPARATOR 
				+ PeerConfiguration.USER_PASSWORD, password);
		
		usersProperties.setProperty(login + PeerConfiguration.USERS_PROPERTIES_SEPARATOR 
				+ PeerConfiguration.USER_PUBLIC_KEY, "");*/
		try {
			/*CommonUtils.saveProperties(usersProperties, userFile, "Users");*/
			
			/*ContainerContext context = new PeerComponentContextFactory(
					new PropertiesFileParser(Main.PEER_PROPERTIES)).createContext();
	        
	        PeerDAO peerDao = new PeerDAO(null);
	        UserDAO userDao = new UserDAO(null);*/
	        
	        PeerAsyncInitializer.getInstance().getComponentClient().addUser(login, password);
	        
	        /*EventCollectorController.getInstance().addUser(login, password, context, peerDao, userDao);*/

			return true;
		/* } catch (IOException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), 
        			"Error while saving userFile", JOptionPane.ERROR_MESSAGE);
			return false;*/
		} catch (CommuneRuntimeException cre) {
			JOptionPane.showMessageDialog(null, cre.getMessage(), 
        			"Error while saving userFile", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
	}

	/**
	 * Creates a new XMPP Acount to the XMPP User added.
	 * @param userName The name of the XMPP User added.
	 * @param userServer The server of XMPP User added.
	 * @param password The password of XMPP User added.
	 */
	private void addXMPPUser(String userName, String userServer, String password) {
		try {
			new XMPPUtils().addUser(
					userServer, 
					userName, 
					password, 
					DEFAULT_SERVER_PORT, 
					DEFAULT_SECURE_PORT);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), 
        			"Error on creating user", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Cancel and close this dialog.
	 * @param evt The event the represents the clicking of the cancel button.
	 */
	private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed
    
    /** Closes this dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog
    
    /**
     * Close this dialog using the status provided.
     * @param retStatus The status of this dialog.
     */
    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }
    
    /**
     * Main method.
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AddUserDialog dialog = new AddUserDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    //private javax.swing.JCheckBox addUserCheckBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton okButton;
    private org.ourgrid.peer.ui.async.gui.UserRegistrationPanel userRegistrationPanel;
    // End of variables declaration//GEN-END:variables
    
    private int returnStatus = RET_CANCEL;
}
